<template>
  <view class="new-or-edit-modal">
    <up-popup v-model:show="show" overlay mode="bottom" touchable minHeight="'300rpx'" maxHeight="'80%'" closeable
      closeOnClickOverlay @close="close" @open="open">
      <scroll-view scroll-y class="modal-content" style="height: 500px;">
        <view class="modal-header">
          <view class="modal-title">新增异常泊位</view>
        </view>
        <up-form labelPosition="left" :model="formModel" :rules="rules" ref="formRef">
          <up-form-item labelWidth="100" label="泊位编号" prop="berthNos">
            <up-input v-model="formModel.berthNos" placeholder="请输入泊位编号，多个用英文逗号隔开" />
          </up-form-item>
          <up-form-item labelWidth="100" label="泊位状态" prop="berthStatus">
            <up-radio-group v-model="formModel.berthStatus">
              <up-radio label="异常" name="0"></up-radio>
              <up-radio label="正常" name="1"></up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item labelWidth="100" label="异常类型" prop="errorType">
            <up-radio-group v-model="formModel.errorType">
              <up-radio label="违停" name="0"></up-radio>
              <up-radio label="障碍物" name="1"></up-radio>
              <up-radio label="非机动车" name="2"></up-radio>
              <up-radio label="其他原因" name="3"></up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item labelWidth="100" label="处理状态" prop="dealStatus">
            <up-radio-group v-model="formModel.dealStatus">
              <up-radio label="待指派" name="0"></up-radio>
              <up-radio label="待处理" name="1"></up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item labelWidth="100" label="同步异常泊位" prop="isSync">
            <up-radio-group v-model="formModel.isSync">
              <up-radio label="否" name="0"></up-radio>
              <up-radio label="是" name="1"></up-radio>
            </up-radio-group>
          </up-form-item>
          <up-form-item labelWidth="100" label="指派人员" prop="accountIds">
            <view class="inspector-select" @click="showInspectorPicker = true">
              <text v-if="selectedInspectorNames">{{ selectedInspectorNames }}</text>
              <text v-else class="placeholder">请选择巡检员</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
          </up-form-item>
          <up-form-item labelWidth="100" label="提醒时间" prop="reminderTime">
            <view class="time-picker-wrapper" @click="showDatePicker = true">
              <view class="time-picker-text">
                {{ formModel.reminderTime ? formatDateTime(formModel.reminderTime) : '请选择提醒时间' }}
              </view>
            </view>
            <up-datetime-picker :show="showDatePicker" v-model="formModel.reminderTime" mode="datetime"
              :show-toolbar="true" @confirm="showDatePicker = false" @cancel="showDatePicker = false" />
          </up-form-item>
          <up-form-item labelWidth="100" label="备注" prop="dealRemark">
            <up-input v-model="formModel.dealRemark" placeholder="请输入备注" />
          </up-form-item>
          <up-form-item labelWidth="100" label="上传图片" prop="images">
            <up-upload :fileList="formModel.images" :maxCount="3" :maxSize="1024 * 1024 * 10" accept="image/*"
              :imageMode="3" :uploadText="'上传图片'" :previewFullImage="true" @afterRead="afterUploadRead"
              @delete="handleDeleteImage" />
          </up-form-item>
        </up-form>
      </scroll-view>

      <view class="modal-footer">
        <up-button type="primary" @click="submit">确认</up-button>
      </view>
    </up-popup>

    <!-- 巡检员选择器 -->
    <up-picker 
      keyName="accountName"
      valueName="accountId"
      :show="showInspectorPicker" 
      :columns="[inspectorColumns]" 
      :closeOnClickOverlay="true"
      @confirm="handleInspectorConfirm" 
      @cancel="showInspectorPicker = false" 
      @close="showInspectorPicker = false"
      multiple
    ></up-picker>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { addErrorBerth, getInspectorList } from '@/api';
const formRef = ref(null);
const loading = ref(false);
const showDatePicker = ref(false);
const showInspectorPicker = ref(false);
const inspectorList = ref([]);
const selectedInspectors = ref([]);

// 定义组件的 props
const props = defineProps({
  show: {
    type: Boolean
  }
});

// 定义组件的 emits
const emit = defineEmits(['update:show', 'confirm']);

// 组件名称
defineOptions({
  name: 'AddModal'
});

// 创建响应式数据  
const show = defineModel<boolean>("show", { default: false });

// 组件挂载时加载巡检员列表
onMounted(() => {
  fetchInspectorList();
});

const formModel = ref(createDefaultModel());

// 获取巡检员列表
const fetchInspectorList = async () => {
  try {
    const res = await getInspectorList();
    if (res.success && Array.isArray(res.data)) {
      inspectorList.value = res.data;
      console.log('巡检员列表数据:', inspectorList.value);
    }
  } catch (error) {
    console.error('获取巡检员列表失败', error);
    uni.showToast({
      title: '获取巡检员列表失败',
      icon: 'error'
    });
  }
};

// 巡检员选择器数据
const inspectorColumns = computed(() => {
  return inspectorList.value;
});

// 处理巡检员选择确认
const handleInspectorConfirm = (e) => {
  selectedInspectors.value = e.value;
  formModel.value.accountIds = selectedInspectors.value.map(item => item.accountId).join(',');
  showInspectorPicker.value = false;
};

// 已选择的巡检员名称
const selectedInspectorNames = computed(() => {
  if (!selectedInspectors.value || selectedInspectors.value.length === 0) return '';
  return selectedInspectors.value.map(item => item.accountName).join(', ');
});

function createDefaultModel() {
  return {
    berthNos: '',
    berthStatus: '0',
    errorType: '0',
    dealStatus: '0',
    isSync: '0',
    accountIds: '',
    reminderTime: Date.now(),
    dealRemark: '',
    images: [],
  };
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

const rules = reactive({
  berthNos: [{ required: true, message: '请输入泊位编号', trigger: 'blur' }],
  berthStatus: [{ required: true, message: '请选择泊位状态', trigger: 'change' }],
  errorType: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
  dealStatus: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  isSync: [{ required: true, message: '请选择是否同步异常泊位', trigger: 'change' }],
  // accountIds: [{ required: false, message: '请输入指派人员ID', trigger: 'blur' }],
  // reminderTime: [{ required: false, message: '请选择提醒时间', trigger: 'change' }],
  // dealRemark: [{ required: false, message: '请输入备注', trigger: 'blur' }],
  // images: [{ required: false, message: '请上传图片', trigger: 'change' }]
});

const submit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    // 处理图片
    let fileUrl = '';
    if (formModel.value.images && formModel.value.images.length > 0) {
      fileUrl = formModel.value.images.join(',');
    }

    console.log('提交的图片URLs:', fileUrl);

    // 调用API添加异常泊位
    const { success, msg } = await addErrorBerth({
      berthStatus: formModel.value.berthStatus,
      errorType: formModel.value.errorType,
      dealStatus: formModel.value.dealStatus,
      isSync: formModel.value.isSync,
      berthNos: formModel.value.berthNos,
      accountIds: formModel.value.accountIds,
      reminderTime: formModel.value.reminderTime + '',
      dealRemark: formModel.value.dealRemark,
      fileUrl: fileUrl
    });

    if (!success) {
      uni.showToast({
        title: msg || '添加失败',
        icon: 'error'
      });
      return;
    }

    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });

    // 关闭弹窗并通知父组件刷新
    close();
    emit('confirm');
  } catch (error) {
    console.error('添加异常泊位失败', error);
    uni.showToast({
      title: '添加失败，请重试',
      icon: 'error'
    });
  } finally {
    loading.value = false;
  }
};

// 打开弹窗
function open() {
  formModel.value = createDefaultModel();
}

// 关闭弹窗
function close() {
  emit('update:show', false);
}

// 处理图片上传后的回调
const afterUploadRead = (event: any) => {
  try {
    // 直接使用本地图片URL
    const { file } = event;

    // 更新图片数组
    if (!formModel.value.images) {
      formModel.value.images = [];
    }

    // 使用本地临时路径
    formModel.value.images.push(file.url || file.path);

    console.log('选择的图片:', formModel.value.images);

    uni.showToast({
      title: '添加成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('添加图片失败', error);
    uni.showToast({
      title: '添加失败',
      icon: 'error'
    });
  }
};

// 处理删除图片
const handleDeleteImage = (event: any) => {
  const { index } = event;
  if (formModel.value.images && formModel.value.images.length > index) {
    formModel.value.images.splice(index, 1);
  }
};
</script>

<style lang="scss" scoped>
.new-or-edit-modal {
  .modal-content {
    box-sizing: border-box;
    padding: 20px;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .modal-title {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .modal-footer {
    padding: 20px;
    display: flex;
    justify-content: center;
  }

  .time-picker-wrapper,
  .inspector-picker-wrapper {
    position: relative;
    width: 100%;

    .time-picker-text,
    .inspector-picker-text {
      width: 100%;
      height: 40px;
      line-height: 40px;
      padding: 0 15px;
      background-color: #f8f8f8;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      color: #606266;
      font-size: 14px;
      cursor: pointer;

      &:active {
        background-color: #f0f0f0;
      }
    }

    :deep(.up-datetime-picker) {
      display: none;
    }
  }
  
  .inspector-select {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px 12px;
  min-height: 36px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.placeholder {
  color: #909399;
}

.date-time-picker {
  width: 100%;
}
}
</style>